package com.kayer.config;

import com.kayer.entity.RestBean;
import com.kayer.entity.vo.AuthorizeVO;
import com.kayer.utils.JwtUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.SecurityFilterChain;

import java.io.IOException;

@Configuration
public class SecurityConfiguration {

    @Resource
    private JwtUtils jwtUtils;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        //配置安全过滤器链
        return http
                .authorizeHttpRequests(conf -> conf
                        //允许所有对/api/auth/**的请求
                        .requestMatchers("/api/auth/**").permitAll()
                        //其他请求需要认证
                        .anyRequest().authenticated()
                )
                .formLogin(conf -> conf
                        //登录处理URL为/api/auth/login
                        .loginProcessingUrl("/api/auth/login")
                        //登录失败处理函数
                        .failureHandler(this::onAuthenticationFailure)
                        //登录成功处理函数
                        .successHandler(this::onAuthenticationSuccess)
                )
                .logout(conf -> conf
                        //注销URL为/api/auth/logout
                        .logoutUrl("/api/auth/logout")
                        //注销成功处理函数
                        .logoutSuccessHandler(this::onLogoutSuccess)
                )
                .csrf(AbstractHttpConfigurer::disable)
                //会话管理，设置为无状态
                .sessionManagement(conf -> conf
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS) //设置为无状态:jwt
                )
                .build();
    }

// 处理认证成功的情况
    private void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        // 设置响应内容类型为JSON
        response.setContentType("application/json;charset=utf-8");
        // 获取认证成功的用户信息
        User user = (User) authentication.getPrincipal();
        // 生成JWT令牌
        String token = jwtUtils.createJwt(user, 1, "Kayer");
        // 创建授权信息对象
        AuthorizeVO authorizeVO = new AuthorizeVO();
        // 设置角色为空
        authorizeVO.setRole("");
        // 设置令牌
        authorizeVO.setToken(token);
        // 设置用户名为Kayer
        authorizeVO.setUsername("Kayer");
        // 将授权信息对象转换为JSON字符串并写入响应
        response.getWriter().write(RestBean.success(authorizeVO).asJsonString());
    }

    private void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(RestBean.failure(401,exception.getMessage()).asJsonString());
    }

    private void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    }
}
